#include "tempshape.h"
#include <QPainter>
#include <QPen>
#include "../scene/customgraphicsscene.h"
#include "flow.h"
#include <QDebug>
#include <QGraphicsSceneMouseEvent>

TempShape::TempShape (const QPointF &pt)
{
	this->setPos(pt);
	this->setVisible(true);
	this->setZValue(100);
}

TempShape::TempShape (const Shape *proto)
{
	this->setPos(proto->pos() + proto->center()
				 + QPointF(qrand()%4-2, qrand()%4-2));
	this->setVisible(true);
	this->setZValue(100);
}

TempShape *TempShape::clone() const
{
	TempShape *newshape = new TempShape(this->pos());
	return newshape;
}


QPainterPath TempShape::shape() const
{
	QPainterPath path;
	path.addEllipse(QPointF(0,0),10,10);
	return path;
}

void TempShape::paint (QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
	painter->setBrush(QColor(245,245,245,100));
	QPen pen(Qt::DashLine);
	pen.setColor(Qt::darkGray);
	painter->setPen(pen);
	painter->drawEllipse(QPoint(0,0), 10,10);
	pen.setColor(Qt::darkGreen);
	painter->setPen(pen);
	painter->setFont(Shape::basicFont());
	QTextOption textoption;
	textoption.setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
	painter->drawText(boundingRect(), "?", textoption);

	if (isSelected())
	{
		setPenAndBrushForSelection(painter);
		painter->drawEllipse(QPoint(0,0), 7,7);
	}
}

QRectF TempShape::boundingRect() const
{
	return QRectF(QPointF(-10,-10), QPointF(10,10));
}

Flow *TempShape::findFlow()
{
	CustomGraphicsScene *scene = static_cast<CustomGraphicsScene *>(this->scene());
	QList<Shape *> shapes = scene->shapes();
	for(int i=0; i<shapes.count(); ++i)
	{
		Flow *f;
		if (f=dynamic_cast<Flow *>(shapes[i]))
		{
			if (f->startShape()==this || f->endShape()==this)
				return f;
		}
	}
	return NULL;
}

Shape *TempShape::findDestinationShape (CustomGraphicsScene *scene)
{
	QList<QGraphicsItem *> items = scene->items(this->pos());
	Shape *sh = NULL;
	for(int i=0; i<items.count(); ++i)
		if (dynamic_cast<Shape *>(items[i]) && !dynamic_cast<TempShape *>(items[i]))
		{
			sh = dynamic_cast<Shape *>(items[i]);
			break;
		}
	return sh;
}

void TempShape::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
{
	CustomGraphicsScene *scene = dynamic_cast<CustomGraphicsScene *>(this->scene());
	Flow *f;
	Shape *sh;
	if (scene && (sh = findDestinationShape(scene)) && (f = findFlow()))
	{
		if (waspressed)	// т.е. если этот элемент не был перемещен
			emit stateIsAboutToBeChangedByUser();

		// Удалить я его здесь не могу, поэтому скрою
		// Он будет уничтожен сценой при создании или открытии диаграммы.

		if (f->startShape()==this && f->canConnectStartTo(sh))
		{
			f->setStartShape(sh);
			scene->takeShape(this)->setVisible(false);
		}

		else if (f->endShape()==this && f->canConnectEndTo(sh))
		{
			f->setEndShape(sh);
			scene->takeShape(this)->setVisible(false);
		}
	}
	QGraphicsItem::mouseReleaseEvent(event);
}
